package com.umbacos.udm.client.presenter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
import com.umbacos.udm.client.arch.HourGlass;
import com.umbacos.udm.client.arch.Popup;
import com.umbacos.udm.client.model.Presenter;
import com.umbacos.udm.client.model.UdmStatus;
import com.umbacos.udm.client.model.View;
import com.umbacos.udm.client.model.UdmStatus.UdmSubscriber;
import com.umbacos.udm.client.presenter.popup.DownloadPopupPresenter;
import com.umbacos.udm.client.view.TrackerView;
import com.umbacos.udm.client.view.TrackerListView;

public class TrackerListPresenter implements Presenter, UdmSubscriber {

	/**
	 * Clicked on the Refresh menu icon
	 */
	class HandlerRefresh implements ClickHandler {
		public void onClick(ClickEvent event) {
			hourglass.wait(true);
			udmStatus.update(UdmStatus.UPDATE_TRACKERS);
		}
	}

	/**
	 * Clicked on the Nuke menu icon
	 */
	class HandlerNuke implements ClickHandler {
		public void onClick(ClickEvent event) {
			Popup pp0=new Popup("Nuke all activities?", null, Popup.POPUP_OK + Popup.POPUP_CANCEL);
			pp0.setAction(null, "nukeall", "", "", udmStatus);
			pp0.showPopup();
		}
	}

	// * Class view of status holder
	public LinkedHashMap<String, TrackerPresenter> bag = new LinkedHashMap<String, TrackerPresenter>();
	private Iterator<String> bagIterator;
	private HourGlass hourglass;
	private int refreshInterval = 0;
	private Timer refreshTimer;

	private TrackerListView tv;

	// * Application status holder
	private UdmStatus udmStatus;

	public void bind(final View mv, final UdmStatus us) {

		udmStatus = us;
		// * Get alerted when files are updated:
		udmStatus.addTrackerSubscription(this);

		hourglass = new HourGlass(null);
		hourglass.wait(true);

		tv = new TrackerListView();
		mv.add(tv);
		
		tv.ibRefresh.addClickHandler(new HandlerRefresh());
		tv.ibNuke.addClickHandler(new HandlerNuke());
		tv.ibDown.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				DownloadPopupPresenter dp=new DownloadPopupPresenter(udmStatus);
				dp.bind();
			}
		});

		tv.lbFreq.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				refreshInterval=Integer.parseInt(tv.lbFreq.getValue(tv.lbFreq.getSelectedIndex()));
				refreshTimer.cancel();
				if (refreshInterval>0) 
					refreshTimer.schedule(1);
				}
		});
		
		// setup timer to refresh list automatically
		refreshTimer = new Timer() {
			@Override
			public void run() {
				udmStatus.update(UdmStatus.UPDATE_TRACKERS);
			}
		};
		refreshTimer.schedule(1);

		hourglass.wait(false);
	}

	public void load(HashMap<String, String> tmpBag) {
		for (Iterator<String> i = tmpBag.keySet().iterator(); i.hasNext();) {
			String key = i.next();
			if (!bag.containsKey(key))
				bag.put(key, new TrackerPresenter(udmStatus, key, tmpBag.get(key)));
			else {
				bag.get(key).setPid(tmpBag.get(key));
			}
		}
	}

	public void refresh() {
		if (bagIterator.hasNext()) {
			final String t = bagIterator.next();
			final TrackerPresenter tracker = bag.get(t);
			tracker.tv.setIcons(tracker.type, tracker.checkIsRunning());
			udmStatus.getTracker(tracker.filename, new RequestCallback() {

				@Override
				public void onError(Request request, Throwable exception) {
				}

				@Override
				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						String txt = response.getText();
						String[] rows = txt.split("\n");
						TrackerView trackV = tracker.tv;
						trackV.htName.setHTML(rows[0]);
						trackV.hpInfo.clear();
						trackV.hpInfo.add(new HTML(rows[rows.length - 1]));
						if (tv.ftTrack.getWidgetIndex(trackV) < 0)
							tv.ftTrack.add(trackV);
						refresh();
					} else 	if (404 == response.getStatusCode()) {
						tv.ftTrack.remove(tracker.tv);
						bag.remove(t);
					}
				}
			});
		}
	}

	@Override
	public void update() {

		load(udmStatus.nfo);
		load(udmStatus.tor);
		load(udmStatus.wgt);
		// load(udmStatus.amu);

		tv.curTrk.setText(TrackerListView.CUR_TRK.replaceAll("X", udmStatus.torrents).replaceAll("Y", udmStatus.wgets));

		if (refreshInterval > 0)
			refreshTimer.schedule(refreshInterval);

		bagIterator = bag.keySet().iterator();
		refresh();
		hourglass.wait(false);
	}
}
